import {Component, NgZone, ViewChild} from '@angular/core';
import {IonicPage, NavController, NavParams, ViewController} from 'ionic-angular';
import {Observable, Subject} from "rxjs";
import {PagingConfig} from "@providers/paging";
import {MapProvider} from "@providers/map";
import {Util} from "@providers/util";

/**
 * Generated class for the AddressMapPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-address-map',
  templateUrl: 'address-map.html',
})
export class AddressMapPage {

  @ViewChild('container') mapElement: any;

  map: any;//地图对象
  marker: any;//地图标记
  addressList: any[] = [];//周边列表
  addressConfig: PagingConfig = new PagingConfig();
  searchTextStream: Subject<String> = new Subject<String>();//搜索流
  searchList: any[] = [];//搜索列表
  isSearch: boolean = false;//是否正在搜索
  markerPosition: any = {};//标记的位置
  isScrolling: boolean = true;//判断滑动到底部是否可以获取更多数据
  isFirst: boolean = true;//判断是否是第一次定位
  param = this.navParams.data;

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private viewCtrl: ViewController,
              private mapService: MapProvider,
              private ngZone: NgZone) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad AddressMapPage');

    this.loadMap();
    //订阅搜索流
    this.searchTextStream
      .debounceTime(600)
      .distinctUntilChanged()
      .subscribe(value => {
        this.mapService.searchPlace(value, {map: ''}).subscribe(result => {
          this.ngZone.run(() => {
            if ("no_data" == result || Util.isNull(value)) {
              this.searchList = [];
            } else {
              if (!this.isSearch) {
                this.isSearch = true;
              }
              this.searchList = result.poiList.pois;
            }
          });
        });
      });
  }

  /**
   * 加载地图
   */
  loadMap() {
    this.mapService.createMap(this.mapElement.nativeElement, {zoom: 18}).then(map => {
      this.map = map;
      this.mapService.displayCurrentPosition().subscribe(data => {
        if (this.param.location && this.isFirst) {
          data.position = this.param.location;
          this.isFirst = false;
        }
        this.map.clearMap();
        if (!this.marker) {
          this.marker = this.mapService.addMarker({'lng': data.position.lng, 'lat': data.position.lat});
        } else {
          this.marker.setPosition(data.position);
        }
        this.map.setFitView();
        this.isScrolling = true;
        this.addressConfig = new PagingConfig();
        this.searchNearby(this.addressConfig).subscribe(data => {
          this.ngZone.run(() => {
            this.addressList = data;
          });
        });
        this.map.on('mapmove', () => {
          this.marker.setPosition(this.map.getCenter());
        });
        this.map.on('moveend', () => {
          this.isScrolling = true;
          this.addressConfig = new PagingConfig();
          this.searchNearby(this.addressConfig).subscribe(data => {
            this.ngZone.run(() => {
              this.addressList = data;
            });
          });
        });
      });
    })
  }

  /**
   *
   * @param data
   * {
   *     "address": "烈山大道258号(工贸家电斜对面)",
   *     "distance": 29,
   *     "location": {
   *         "M": 113.37284699999998,
   *         "O": 31.717841,
   *        "lat": 31.717841,
   *         "lng": 113.372847
   *     },
   *     "name": "发源地(烈山大道旗舰店)"
   * }
   */
  dismiss(data?: any) {
    if (data) {
      this.mapService.poToAddress([data.location.lng, data.location.lat]).subscribe(value => {
        data.addressComponent = value.addressComponent;
        this.viewCtrl.dismiss(data);
      });
    } else {
      this.viewCtrl.dismiss();
    }
  }

  //设置周边街道明细
  private searchNearby(pageConfig: PagingConfig) {
    return Observable.create(observer => {
      this.mapService.poToAddress([this.marker.getPosition().lng, this.marker.getPosition().lat]).subscribe(data => {
        this.ngZone.run(() => {
          this.markerPosition.name = data.formattedAddress.substring((data.addressComponent.province + data.addressComponent.city + data.addressComponent.district).length);
          this.markerPosition.address = data.addressComponent.street + data.addressComponent.streetNumber;
          this.markerPosition.addressComponent = data.addressComponent;
          this.markerPosition.location = this.marker.getPosition();
        });
      });
      let data = [];
      this.mapService.searchNearby(
        [this.marker.getPosition().lng, this.marker.getPosition().lat],
        '',
        500, {pageIndex: pageConfig.skip + 1}).subscribe(result => {
        if ("no_data" == result) {
          data = [];
        } else {
          data = result.poiList.pois;
        }
        if (data.length < 10) {
          pageConfig.isEnd = true;
        }
        pageConfig.skip++;
        observer.next(data);
        observer.complete();
      });
    });
  }

  /**
   * 搜索事件
   * @param data
   */
  search(data: string) {
    this.searchTextStream.next(data);
  }

  /**
   * 输入框获得焦点时调用
   */
  changeIsSearch() {
    this.ngZone.run(() => {
      this.isSearch = true;
    })
  }

  /**
   * 下拉刷新
   */
  getMoreDatas(e) {
    let scrollHeight = e.target.scrollHeight;
    let offsetHeight = e.target.offsetHeight;
    let scrollTop = e.target.scrollTop;
    if (scrollHeight - offsetHeight - scrollTop < 100 && this.isScrolling) {
      this.isScrolling = false;
      console.log('执行');
      this.searchNearby(this.addressConfig).subscribe(data => {
        this.addressList.push.apply(this.addressList, data);
        if (!this.addressConfig.isEnd) {
          this.isScrolling = true;
        }
      });
    }

  }

}
